<template>
  <div class="ai-chat-container">
    <!-- 聊天消息区域 -->
    <div class="chat-messages" ref="messagesContainer">
      <div 
        v-for="(message, index) in messages" 
        :key="index"
        :class="['message', message.role === 'user' ? 'user-message' : 'assistant-message']"
      >
        <div class="avatar">
          {{ message.role === 'user' ? '👤' : '🤖' }}
        </div>
        <div class="message-content">
          <div v-if="message.role === 'user'" class="text">
            {{ message.content }}
          </div>
          <div v-else class="text" v-html="message.content"></div>
        </div>
      </div>
      
      <!-- 加载指示器 -->
      <div v-if="isLoading" class="loading-indicator">
        <div class="typing-dots">
          <span></span>
          <span></span>
          <span></span>
        </div>
        <span>AI正在思考中...</span>
      </div>
    </div>

    <!-- 输入区域 -->
    <div class="input-area">
      <textarea
        v-model="inputText"
        placeholder="请输入您的问题..."
        @keydown.enter.exact.prevent="sendMessage"
        :disabled="isLoading"
        rows="3"
      ></textarea>
      <button 
        @click="sendMessage" 
        :disabled="!inputText.trim() || isLoading"
        class="send-button"
      >
        {{ isLoading ? '发送中...' : '发送' }}
      </button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount, nextTick } from 'vue'

// 类型定义
interface ChatMessage {
  role: 'user' | 'assistant'
  content: string
  timestamp: number
}

// 响应数据
const messages = ref<ChatMessage[]>([])
const inputText = ref('')
const isLoading = ref(false)
const messagesContainer = ref<HTMLElement | null>(null)
const abortController = ref<AbortController | null>(null)

// 自动滚动到底部
const scrollToBottom = () => {
  nextTick(() => {
    if (messagesContainer.value) {
      messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight
    }
  })
}

// 简化的流式处理 - 直接累积所有数据
const handleStreamResponse = async (response: Response) => {
  if (!response.body) {
    throw new Error('响应体为空')
  }

  const reader = response.body.getReader()
  const decoder = new TextDecoder()
  let accumulatedContent = ''

  try {
    while (true) {
      const { done, value } = await reader.read()
      
      if (done) {
        console.log('流式响应结束')
        break
      }

      // 解码数据块
      const chunk = decoder.decode(value, { stream: true })
      console.log('接收到的原始数据:', chunk)
      
      // 简单处理：累积所有内容
      accumulatedContent += chunk
      
      // 获取最后一条助手消息并更新内容
      const lastMessage = messages.value[messages.value.length - 1]
      if (lastMessage && lastMessage.role === 'assistant') {
        // 直接显示累积的内容（不解析JSON，直接显示原始文本）
        lastMessage.content = accumulatedContent
        scrollToBottom()
      }
    }
  } finally {
    reader.releaseLock()
  }
}

// 发送消息
const sendMessage = async () => {
  const question = inputText.value.trim()
  if (!question || isLoading.value) return

  try {
    isLoading.value = true
    abortController.value = new AbortController()

    // 添加用户消息
    messages.value.push({
      role: 'user',
      content: question,
      timestamp: Date.now()
    })

    // 添加初始助手消息（空内容）
    messages.value.push({
      role: 'assistant',
      content: '',
      timestamp: Date.now()
    })

    // 清空输入框
    inputText.value = ''
    scrollToBottom()

    // 获取token
    const userData = localStorage.getItem('user')
    const token = userData ? JSON.parse(userData).token : ''

    if (!token) {
      throw new Error('未找到用户token')
    }

    console.log('开始发送请求...')

    // 发送请求
    const response = await fetch('http://localhost:8090/qa/ai/jsonToSay', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'token': token
      },
      body: JSON.stringify({ message: question }),
      signal: abortController.value.signal
    })

    console.log('响应状态:', response.status, response.statusText)

    if (!response.ok) {
      throw new Error(`HTTP错误: ${response.status} ${response.statusText}`)
    }

    // 处理流式响应
    await handleStreamResponse(response)

  } catch (error) {
    console.error('请求失败:', error)
    
    // 如果是取消请求，不显示错误
    if (error instanceof Error && error.name === 'AbortError') {
      return
    }

    // 更新最后一条助手消息显示错误
    const lastMessage = messages.value[messages.value.length - 1]
    if (lastMessage && lastMessage.role === 'assistant') {
      lastMessage.content = `❌ 请求失败: ${error instanceof Error ? error.message : '未知错误'}`
      scrollToBottom()
    }
  } finally {
    isLoading.value = false
    abortController.value = null
  }
}

// 组件卸载时取消请求
onBeforeUnmount(() => {
  if (abortController.value) {
    abortController.value.abort()
  }
})

// 初始化时滚动到底部
onMounted(() => {
  scrollToBottom()
})
</script>

<style scoped>
.ai-chat-container {
  max-width: 800px;
  margin: 0 auto;
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: #f8f9fa;
}

.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.message {
  display: flex;
  gap: 12px;
  max-width: 100%;
}

.user-message {
  flex-direction: row-reverse;
}

.assistant-message {
  flex-direction: row;
}

.avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20px;
  flex-shrink: 0;
  background: #e9ecef;
}

.user-message .avatar {
  background: #007bff;
  color: white;
}

.message-content {
  max-width: 70%;
  padding: 12px 16px;
  border-radius: 12px;
  background: white;
  box-shadow: 0 1px 3px rgba(0,0,0,0.1);
}

.user-message .message-content {
  background: #007bff;
  color: white;
}

.text {
  word-wrap: break-word;
  line-height: 1.5;
  white-space: pre-wrap;
}

.input-area {
  padding: 20px;
  background: white;
  border-top: 1px solid #e9ecef;
  display: flex;
  gap: 12px;
  align-items: flex-end;
}

textarea {
  flex: 1;
  padding: 12px;
  border: 1px solid #dee2e6;
  border-radius: 8px;
  resize: none;
  font-family: inherit;
  font-size: 14px;
  line-height: 1.5;
}

textarea:focus {
  outline: none;
  border-color: #007bff;
  box-shadow: 0 0 0 2px rgba(0, 123, 255, 0.25);
}

.send-button {
  padding: 12px 24px;
  background: #007bff;
  color: white;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 500;
  transition: background-color 0.2s;
}

.send-button:hover:not(:disabled) {
  background: #0056b3;
}

.send-button:disabled {
  background: #6c757d;
  cursor: not-allowed;
}

.loading-indicator {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px 16px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 1px 3px rgba(0,0,0,0.1);
  color: #6c757d;
  font-size: 14px;
}

.typing-dots {
  display: flex;
  gap: 4px;
}

.typing-dots span {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background: #6c757d;
  animation: typing 1.4s infinite ease-in-out;
}

.typing-dots span:nth-child(1) { animation-delay: -0.32s; }
.typing-dots span:nth-child(2) { animation-delay: -0.16s; }

@keyframes typing {
  0%, 80%, 100% {
    transform: scale(0.8);
    opacity: 0.5;
  }
  40% {
    transform: scale(1);
    opacity: 1;
  }
}

/* 滚动条样式 */
.chat-messages::-webkit-scrollbar {
  width: 6px;
}

.chat-messages::-webkit-scrollbar-track {
  background: #f1f1f1;
}

.chat-messages::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.chat-messages::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}
</style>